var express = require('express');
var router = express.Router();
var { cartmodel } = require('../database/models/userModel.js')
//加入购物车
router.post('/', (req, res) => {
    let{id,userid}=req.body
    cartmodel.find({ id, userid }).then(result => {//查找购物车
        if (result.length == 0) {//如果查出来的长度为0
            new cartmodel(req.body).save().then(result => {
                console.log("新增购物车",result);
            res.send({
                code: 111,
                msg:'加入成功'
                })
            })
            return
        }
        // 如果查出来有长度,就应该更新，而不是新增
        let { _id, product_quantity } = result[0]//提取已有商品的用户id和购物车商品数量
        product_quantity += req.body.product_quantity
        cartmodel.updateOne({ _id }, { product_quantity }).then(result => {
            res.send({
                code: 111,
                msg:'更新成功'
            })
        })
    })
    
})
// 加载购物车
router.get('/', (req, res) => {
    // console.log(req.query);
    let {userid}=req.query
    cartmodel.find({userid}).then(result => {
        // console.log('数据库购物车',result);
        res.send({
            code: 111,
            msg: '购物车加载成功',
            data:result
        })
    })
})
// 删除购物车
router.delete('/', (req, res) => {
    console.log('购物车删除',req.query);
    let {userid,id}=req.query
    cartmodel.deleteOne({ userid, id }).then(result => {
        console.log(result);
            res.send({
                code: 111,
                msg: '删除成功',
                data:result
            })
    })
    }
)
module.exports = router;